package popedom

import (
	"strconv"
	"strings"

	"shqsoft.cn/pas3ui/base"
	"shqsoft.cn/pas3ui/popedom/entity"
)

//ValidateUserLogin 验证用户登录
func ValidateUserLogin(userNo string, password string) (bool, bool, *entity.SysUser, error) {
	user := entity.SysUser{}
	err := base.MYDB.Where(`NO=?`, userNo).First(&user).Error
	if err != nil {
		return false, false, nil, err
	}
	pwdH := HashPassword(userNo, password)
	if pwdH != user.Password {
		return false, false, nil, err
	}
	pwdH = HashPassword(userNo, "00000000")
	if pwdH == user.Password {
		return true, true, &user, err
	}
	return true, false, &user, err
}

//ValidateUserPermissionByType 验证用户拥有权限的权限类型
func ValidateUserPermissionByType(userID int, permissionID int, permissionTypeID string) (bool, error) {
	uptype, err := GetUserPermFormRedis(userID, permissionID)
	if err != nil {
		return false, err
	}
	for _, ut := range uptype {
		if ut == permissionTypeID {
			return true, nil
		}
	}
	return false, nil
}

//GetUserPermissionTypes 获取用户在某个权限的所有权限类型
func GetUserPermissionTypes(userID int, permissionID int) ([]string, error) {
	return GetUserPermFormRedis(userID, permissionID)
}

//ValidateUserPermission 验证用户是否有权限
func ValidateUserPermission(userID int, permissionID int) (isOk bool, err error) {
	cPerms := base.RedisCli.HGet(rctx, "permission", strconv.Itoa(permissionID)).Val()
	if cPerms == "" {
		isOk, err = validateUserPermission(userID, permissionID)
	} else {
		cPermsArr := strings.Split(cPerms, ",")
		for _, cp := range cPermsArr {
			cpInt, _ := strconv.Atoi(cp)
			isOk, err = ValidateUserPermission(userID, cpInt)
			if isOk {
				break
			}
		}
	}
	return isOk, err
}
func validateUserPermission(userID int, permissionID int) (bool, error) {
	pts, err := GetUserPermFormRedis(userID, permissionID)
	if err != nil {
		return false, err
	}
	if len(pts) > 0 {
		return true, nil
	}
	return false, nil
}

//IsHasRole 验证用户是否拥有角色
func IsHasRole(userID int, roleID int) (bool, error) {
	rps, err := GetUserRolesFormRedis(userID)
	if rps == nil {
		return false, nil
	}
	if err != nil {
		return false, err
	}
	for _, r := range rps {
		if r == strconv.Itoa(roleID) {
			return true, nil
		}
	}
	return false, nil
}

//IsDispIdno 验证用户是否可查看证件号码
func IsDispIdno(userID int) (bool, error) {
	rps, err := GetUserRolesFormRedis(userID)
	if err != nil {
		return false, err
	}
	var count int64
	err = base.MYDB.Model(&entity.SysRole{}).Where(`RoleId in (?) and CanIdno=1`, rps).Count(&count).Error
	if err != nil {
		return false, err
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}
